import { useState, useEffect } from 'react';
import { FlatList, StyleSheet, TouchableHighlight, TouchableOpacity, Text, Button, View, Image, TextInput, Dimensions, Animated } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { List, Picker, DatePicker, InputItem } from 'antd-mobile-rn';
import { useAuth, baseURL } from '../../context/AuthProvider';
import axios from '../../api/axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as FileSystem from 'expo-file-system';
const data = require('@bang88/china-city-data')
const Btn = ({ style, children, ...rest }) => {
  return <TouchableOpacity {...rest}
    style={{ borderRadius: 5, justifyContent: 'center', alignItems: 'center', ...style }}>
    <Text style={{ color: 'white' }}>{children}</Text>
  </TouchableOpacity>
}
const Btn1 = ({ style, children, ...rest }) => {
  return <TouchableOpacity {...rest}
    style={{ borderRadius: 5, justifyContent: 'center', alignItems: 'center', ...style }}>
    <Text style={{ color: 'white', fontSize: 13 }}>{children}</Text>
  </TouchableOpacity>
}
// 上传图片api调用
async function uploadImage(params) {
  const formData = new FormData();
  formData.append('file', {
    uri: params.uri,
    type: params.type,
    name: params.fileName,
  });
  return await fetch(`apiurl`, {
    method: 'post',
    body: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
  }).then((response) => {
    return response.json()
  })
}

const Accounts = () => {
  const { user } = useAuth();
  const { setUser } = useAuth()
  // console.log(user);
  // console.log(user.username);
  const [userName, setUserName] = useState(user.username)
  const [nickName, setNickName] = useState(user.nickname)
  const [password, setPassword] = useState(user.password)
  const [userSignature, setUserSignature] = useState(user.signature)
  const [birthday, setBirthday] = useState(user.birthday)
  const [city, setCity] = useState(user.city)
  const [phone, setPhone] = useState(user.mobile)

  const [utext, setUtext] = useState(true)
  const [baseImg, setBaseImg] = useState({})
  const [imageUrl, setImageUrl] = useState();
  const [pickerValue, setPickerValue] = useState([])
  const [value, setValue] = useState(JSON.parse(user.city))
  const [selectTime, setSelectTime] = useState();
  const [changeAva, setChangeAva] = useState(false)
  const [label, setLabel] = useState('')
  function handleYMD(t) {
    let add0 = m => m > 9 ? m : '0' + m;
    console.log(`${t.getFullYear()}-${add0(t.getMonth() + 1)}-${add0(t.getDate())}`);
    return `${t.getFullYear()}-${add0(t.getMonth() + 1)}-${add0(t.getDate())}`
  }
  console.log(user.city);
  onChange = (value) => {
    console.log(1111111);
    setValue(value)
  }
  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [3, 3],
      quality: 1,
    });

    console.log(result);

    if (!result.canceled) {
      let base = "data:image/jpeg;base64," + await FileSystem.readAsStringAsync(result.assets[0].uri, { encoding: 'base64' })
      console.log(base);
      setImageUrl(base);
      console.log(imageUrl);
    }
  }
  const upChange = async () => {
    console.log('eeeeeeeeeeee');
    console.log(label);
    let arr = label.split(" ")
    let cityname = arr[arr.length-1].slice(0, -1)
    // let arr1 = label.split("市辖区")
    console.log(cityname);
    if (phone) {
      if (checkModbile(phone)) {
        console.log(222222222);
        // console.log(phone);
        // console.log(typeof(value));
        // console.log(JSON.stringify(value));
        let reg1 = new RegExp(" ", "g"); // 加'g'，删除字符串里所有的"a"
        let str = phone.replace(reg1, "");
        console.log(str);
        axios.post('/users/changeuser', {
          username: userName, nickname: nickName, password: password, cityname: cityname,
          signature: userSignature, avatar: imageUrl ? imageUrl : user.avatar, userid: Number(user.userid),
          birthday: birthday, mobile: Number(str), city: JSON.stringify(value)
        }).then(res => {
          // console.log(res);
          console.log(1234);
          if (res.code == 200) {
            axios.post('/users/getmyuser', { userid: user.userid }).then(res => {
              if (res.code == 200) {
                // console.log(res.data[0]);
                console.log(5678);
                console.log(res.data[0]);
                setUser(res.data[0]);
                AsyncStorage.setItem('user', JSON.stringify(res.data[0]), function (err) {
                  if (err) {
                    alert('修改失败')
                  } else {
                    alert("修改成功");
                  }
                })
                console.log(99999);
              }
            })
          }
        })
      }
    } else {
      axios.post('/users/changeuser', {
        username: userName, nickname: nickName, password: password, cityname: cityname,
        signature: userSignature, avatar: imageUrl ? imageUrl : user.avatar, userid: user.userid,
        birthday: birthday, mobile: Number(phone), city: JSON.stringify(value)
      }).then(res => {
        // console.log(res);
        console.log(1234);
        if (res.code == 200) {
          axios.post('/users/getmyuser', { userid: user.userid }).then(res => {
            if (res.code == 200) {
              // console.log(res.data[0]);
              console.log(5678);
              setUser(res.data[0]);
              AsyncStorage.setItem('user', JSON.stringify(res.data[0]), function (err) {
                if (err) {
                  alert('修改失败')
                } else {
                  alert("修改成功");
                }
              })
              console.log(99999);
            }
          })
        }
      })
    }


  }
  const checkModbile = (mobile) => {
    var reg1 = new RegExp(" ", "g"); // 加'g'，删除字符串里所有的"a"
    var str = mobile.replace(reg1, "");
    console.log(mobile);
    var re = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0-9]{1})|(15[0-3]{1})|(15[4-9]{1})|(18[0-9]{1})|(199))+\d{8})$/;
    var result = re.test(Number(str));
    console.log(result);
    console.log(11111);
    if (!result) {
      alert("手机号码格式不正确！");
      return false;//若手机号码格式不正确则返回false
    }
    return true;
  }
  return (
    <View style={styles.container}>
      <Image source={require('../../../images/mine/changebg.jpg')} style={{ width: '100%', height: '100%' }} />
      <View style={styles.modalView}>
        <View style={styles.centeredView}>
          <View style={styles.mcon}>
            {
              imageUrl
                ? <Image
                  source={{ uri: imageUrl }}
                  style={styles.topImg}
                />
                : <Image source={user.avatar ? { uri: baseURL+user.avatar } : require('../../../images/mine/1.jpg')} style={styles.topImg}></Image>
            }
            <Btn1 style={{ backgroundColor: '#06f', width: '30%', height: 30, marginLeft: '10%' }}
              onPress={pickImage}
            >选择图片</Btn1>
          </View>

          <View style={styles.con}>
            <Text>用户名</Text>
            <TextInput
              style={styles.Tinput}
              onChangeText={text => setUserName(text)}
              value={userName}
            />
          </View>
          <View style={styles.con}>
            <Text>密码</Text>
            <TextInput maxLength={250}
              style={styles.Tinput}
              secureTextEntry={true}
              onChangeText={text => setPassword(text)}
              value={password}
            />
          </View>
          <View style={styles.con}>
            <Text>昵称</Text>
            <TextInput multiline={true} maxLength={250}
              style={styles.Tinput}
              onChangeText={text => setNickName(text)}
              value={nickName}
            /></View>
          <View style={styles.con}>
            <Text>签名</Text>
            <TextInput multiline={true} maxLength={250}
              style={styles.Tinput}
              onChangeText={text => setUserSignature(text)}
              value={userSignature}
            /></View>
          {/* <View style={styles.con}>
            <Text>生日</Text>
            <View style={styles.picker2}>
              <DatePicker
                mode="date"
                maxDate={new Date()}
                value={selectTime}
                format={'YYYY-MM-DD'}
                onChange={time => setSelectTime(time)}
              >
                <List.Item arrow="horizontal" style={styles.picker1} useNativeDriver={true}></List.Item>
              </DatePicker>
            </View>
          </View> */}
          <View style={styles.con}>
            <Text>城市</Text>
            <View style={styles.picker2}>
              <Picker itemStyle={{ color: '#5D5D5D', fontSize: 14 }}
                data={data} useNativeDriver={true}
                cols={3}
                value={value}
                format={(labels) => {
                  let kk = labels.join(' ')
                  setLabel(kk)
                  return kk
                }}
                onChange={onChange}>
                <List.Item arrow="horizontal" style={styles.picker1} useNativeDriver={true} ></List.Item>
              </Picker>
            </View>
          </View>
          <View style={styles.con}>
            <Text>手机号</Text>
            <InputItem style={[styles.Tinput, { backgroundColor: '#fff' }]}
              type="phone"
              value={phone}
              onChange={(value) => {
                setPhone(value)
              }}
              placeholder="手机号">
            </InputItem>
          </View>

          {/* </View> */}
          <Btn
            onPress={upChange}
            style={{ width: '100%', height: 40, backgroundColor: '#06f', marginTop: 20 }}>
            确认修改
          </Btn>
        </View>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    // backgroundImage: url('../../assets/bg.png'),
    height: '100%',

  },
  modalView: {
    backgroundColor: 'rgba(255, 255, 255, 0.7)',
    padding: 20,
    width: '90%',
    position: 'absolute',
    flexDirection: 'row'
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22,
    marginTop: 0,
    width: '70%',
    margin: 20,
  },
  con: {
    width: '100%',
    flexDirection: 'row',
    justifyContent: 'space-between',
    margin: 5,
    alignItems: 'center'
  },
  mcon: {
    width: '100%',
    flexDirection: 'row',
    margin: 5,
    alignItems: 'center',

  },
  Tinput: {
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    width: '80%',
    paddingLeft: 10,
    marginLeft: '5%'
  },
  picker2: {
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    width: '80%',
    paddingLeft: 10,
    marginLeft: '5%',
    backgroundColor: '#fff',
    fontSize: 12
  },
  picker1: {
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    width: Dimensions.get('window').width * 0.9,
    // width: 0.9*0.7*0.92*Dimensions.get('window').width,
    paddingLeft: 0,
    marginLeft: -Dimensions.get('window').width * 0.32,
    backgroundColor: 'rgba(247,247,246,0)',
    borderColor: 'rgba(247,247,246,0)',
    fontSize: 12
  },
  upImg: {
    flexDirection: 'row',
    backgroundColor: 'white',
    borderColor: 'lightgray',
    borderRadius: 5,
    borderWidth: 1,
    borderStyle: 'solid',
    padding: 8,
    marginLeft: '10%'
  },
  topImg: {
    height: 0.25 * 0.9 * 0.7 * Dimensions.get('window').width,
    width: 0.25 * 0.9 * 0.7 * Dimensions.get('window').width,
    borderRadius: 50,
    borderWidth: 4,
    borderColor: '#fff',
  },
});

export default Accounts; 